<script>
import { deepClone } from '@/utils';
import { xhrGetPageComponent, xhrSetComponent, autoRequest } from '@/api/page';

export default {
  name: 'Base',
  props: {
    componentName: {
      type: String,
      default: ''
    },
    fromId: {
      type: Number,
      default: 0
    },
    rootId: {
      type: Number,
      default: 0
    },
    debug: { // 是否处于调试状态
      type: Boolean,
      default: false
    },
    pid: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      configData: {},
      editDialogFormVisible: false,
      listLoading: false,
      requestList: []
    }
  },

  created() {
    this.pageId = this.$route.meta.pageId
    this.requestList = this.$route.meta.requestList
    this.loadPage()
    this.onCreated()
    this.doSearch()
  },

  mounted() {
  },

  methods: {
    onCreated: function() {
    },
    doSearch: function() {
    },
    editPage: function() {
      this.editDialogFormVisible = true
    },
    updatePage: function(needRefreshPage) {
      needRefreshPage = needRefreshPage || false
      const c_data = deepClone(this.configData)
      const data = {
        id: this.fromId, pageId: this.pageId, configData: JSON.stringify(c_data), componentName: this.componentName, pid: this.pid
      }
      xhrSetComponent(data)
        .then(resp => {
          this.$message.success('添加成功')
          this.editDialogFormVisible = false
          if (needRefreshPage) {
            window.location.reload()
          } else {
            this.reloadPage()
          }
        })
        .catch(err => {
          this.$message.error(err)
        })
    },
    loadPage: function() {
      for (const i in this.$route.meta.pageComponents) {
        if (this.$route.meta.pageComponents[i].id === this.fromId) {
          this.configData = this.$route.meta.pageComponents[i].configData
        }
      }
      this.$forceUpdate()
    },
    reloadPage: function() {
      xhrGetPageComponent({ pageId: this.pageId })
        .then(resp => {
          for (const i in resp.data.list) {
            resp.data.list[i].configData = JSON.parse(resp.data.list[i].configData)
          }
          this.$route.meta['pageComponents'] = resp.data.list
          this.loadPage()
        })
        .catch(err => {
          this.$message.error(err)
        })
    },
    handleFilter() {
      this.listLoading = true
      this.listQuery.offset = 0
      this.listQuery.page = 1
      this.doSearch()
    },
    sendRequest: function(requests) {
      autoRequest(requests.url, requests.model, requests._params, requests._data)
        .then(resp => {
          this.$route.meta.pageData[this.rootId][requests.requestName] = resp.data
          if (requests.message.length > 0) {
            this.$message.success(requests.message + '成功')
          }
          this.$forceUpdate()
        })
        .catch(err => {
          this.$message.error(err)
        })
    }
  }
}
</script>
